
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;


public class QuizController
{

	public QuizController(JFrame frame, Quiz quiz)
	{
		itsFrame = frame;
		itsQuiz = quiz;
		results =  new int[itsQuiz.size()];
		for(int i = 0; i < itsQuiz.size(); ++i)
		{
			results[i] = -1;
		}
	}
	
	public void go()
	{
		StartView view = new StartView(itsQuiz.getQuizname(), this);
		view.display(itsFrame);
	}
	
	public void done()
	{
		System.exit(0);
	}
	
	public void start()
	{
		currentQuestion = 0;
		ask();
	}
	
	private void ask()
	{
		Question q = itsQuiz.getQuestion(currentQuestion);
		if(q != null)
		{
			boolean showPrev = currentQuestion > 0;
			boolean showNext = currentQuestion < itsQuiz.size() - 1;
			QuestionView view = new QuestionView(q, this, showPrev);
			view.display(itsFrame);
		}
	}
	
	public void prev()
	{
		currentQuestion--;
		ask();
	}
	
	public void next()
	{
		currentQuestion++;
		if(currentQuestion < itsQuiz.size())
		{
			ask();
		}
		else
		{
			results();
		}
	}
	
	public void results()
	{
		boolean status[] = new boolean[itsQuiz.size()];
		for(int i = 0; i < itsQuiz.size(); ++i)
		{
			status[i] = (results[i] == itsQuiz.getQuestion(i).getAnswer());
		}
		ResultsModel model = new ResultsModel(status);
		ResultsView view = new ResultsView(this, model);
		view.display(itsFrame);
	}
	
	public void showAnsweredQuestion(int index, JDialog parent)
	{
		//JOptionPane.showMessageDialog(null, "result for question: " + Integer.toString(index));
		AnsweredQuestionView view = new AnsweredQuestionView(itsQuiz.getQuestion(index), results[index]);
		view.display(parent);
	}
	
	public void setResult(int result)
	{
		results[currentQuestion] = result;
	}
	
	public int getCurrentResult()
	{
		return results[currentQuestion];
	}
	
	int currentQuestion = 0;
	private Quiz itsQuiz;
	private JFrame itsFrame;
	private int[] results;
}
